package ru.amse.jsynchro.net.stream;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.OutputStream;

public class ProtocolOutputStream extends LimitedOutputStream {
    private ObjectInput objectIn;
    
    protected ProtocolOutputStream(OutputStream out) {
        super(out);
    }
    
    public ProtocolOutputStream(OutputStream out, long limit, ObjectInput objectIn) {
        super(out, limit);
        this.objectIn = objectIn;
        bufferPos = 0;
        this.objectIn = objectIn;
    }
    
    public void write(int b) throws IOException {
        limit--;
        if (limit >= 0) {
            buffer[bufferPos++] = (byte) b;
            
            if (bufferPos == BUFFER_SIZE) {
                out.write(buffer);
                bufferPos = 0;
                try {
                    objectIn.readObject();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        if ((limit == 0) && (bufferPos != 0)) {
            out.write(buffer, 0, bufferPos);
            try {
                objectIn.readObject();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        
    }
}
